Stream sorted() Method Example In Java

Stream interface provides a sorted() method to sort a list. The sorted() method returns a sorted stream according to the natural order. If the elements are not comparable, it throws java.lang.ClassCastException.

  1. Stream sorted() method is an intermediate operation.
  2. Stream interface provides a sorted() method to sort a list.
  3. Stream sorted() method returns a sorted stream according to the natural order.
  4. If the elements are not comparable, it throws java.lang.ClassCastException.

Syntax:

 Stream<T<> sorted()

Syntax of sorted method with comparator in argument:

 Stream<T<> sorted(Comparator<? Super T> comparator)  

Example of stream sorted method

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class StreamSortedExample {
  public static void main ( String args[]){ 
    Integer[] numbers = { 100, 20, 13, 440, 5, 16, 7, 28, 2, 11, 1 };
    ListInteger> sortedList = 
    Arrays.asList(numbers).stream() 
        .sorted()
        .collect( Collectors.toList() );
                
    System.out.println( ""Sorted list : "+ sortedList ); 
  }
}


Output:
    Sorted list : [1, 2, 5, 7, 11, 13, 16, 20, 28, 100, 440]

Example of stream sorted method with forEach method

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class StreamSortedExample {
  public static void main (String args[]){
    Integer[] numbers = { 100, 20, 13, 440, 5, 16, 7, 28, 2, 11, 1 };
    List<Integer> sortedList = 
    Arrays.asList( numbers ).stream()
            .sorted()
            //forEach with method reference
            .forEach( System.out :: println );
 }
}
 
Output:
    1
    2
    5
    7
    11
    13
    16
    20
    28
    100
    440

Example of sorted method with comparator in argument:

public class Students {
    private Integer age;
    private String name;

    Students(Integer age,String name){
        this.age=age;
        this.name=name;
    }

    public String toString() {
        return this.age + ", "+ this.name;
    }
}

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;
public class SortedExampleWithComparator {
  public static void main ( String args[]){
    List<Students> studentsList = new ArrayList<Students>();
    studentsList.add( new Students( 18, "Pankaj" ));
    studentsList.add( new Students( 20, "Prakash" ));
    studentsList.add( new Students( 16, "Karim" ));
    studentsList.add( new Students( 19, "Shyam" ));

    studentsList
    .stream()
    //comparator
    .sorted(( s1, s2 ) -> s1.age.compareTo( s2.age ))
    //forEach with method reference
    .forEach( System.out :: println );
  }             
}

Output:
    16, Karim
    18, Pankaj
    19, Shyam
    20, Prakash